
package com.haiyou.common.util.system;

import java.lang.management.ManagementFactory;
import java.math.BigDecimal;
import java.util.Collection;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.TimeUnit;

import com.haiyou.common.system.SystemProperties;

import lombok.extern.slf4j.Slf4j;

/**
 * 
 * 
 * @Description: 系统工具类
 * @author xingyuan
 * @date 2022年2月15日 下午5:19:34
 */
@Slf4j
public class SystemUtils {

	/**
	 * 获取项目根目录
	 * 
	 * @return
	 */
	public static String getServerHome() {
		return SystemProperties.getString("user.dir");
	}

	/**
	 * 获取当前的主线程id(进程id)
	 *
	 * @return
	 */
	public static String getPid() {
		return ManagementFactory.getRuntimeMXBean().getName().split("@")[0];
	}

	/**
	 * 是否为win系统
	 * 
	 * @return
	 */
	public static boolean isWindows() {
		return System.getProperty("os.name").toLowerCase().contains("windows");
	}

	/**
	 * 是否为linux系统
	 * 
	 * @return
	 */
	public static boolean isLinux() {
		return System.getProperty("os.name").toLowerCase().contains("linux");
	}

	public static void sleep(long timeout, TimeUnit unit) {
		try {
			unit.sleep(timeout);
		} catch (InterruptedException e) {
			log.error(e.getMessage(), e);
			return;
		}
	}

	/**
	 * 获取内存使用率
	 * 
	 * @return
	 */
	public static double memoryUsed() {
		long freeMemory = Runtime.getRuntime().freeMemory();
		long totalMemory = Runtime.getRuntime().totalMemory();
		double d = (totalMemory - freeMemory * 1.0d) / totalMemory;
		BigDecimal bg = new BigDecimal(d);
		double result = bg.setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue();
		return result;
	}

	public static Map<Thread, StackTraceElement[]> threadStackTraces() {
		return Thread.getAllStackTraces();
	}

	public static Set<Thread> threadSet() {
		Map<Thread, StackTraceElement[]> maps = threadStackTraces();
		return maps.keySet();
	}

	public static Collection<StackTraceElement[]> threadValues() {
		Map<Thread, StackTraceElement[]> maps = threadStackTraces();
		return maps.values();
	}

	public static void main(String[] args) {
		Set<Thread> threads = threadSet();
		threads.forEach(t -> System.err.println(t));
	}

}
